package leetcode_acm.stackAndQueue;

import org.junit.Test;

import java.util.ArrayDeque;
import java.util.HashSet;
import java.util.Set;

/**
 * 功能描述
 *
 * @author: 张庭杰
 * @date: 2023年03月22日 15:00
 */
public class EvalRPN {
    public int evalRPN(String[] tokens) {
        if(tokens == null || tokens.length == 0){
            return 0;
        }
        Set<String> set = new HashSet<>();
        set.add("+");set.add("-");set.add("*");set.add("/");
        ArrayDeque<Integer> arrayDeque = new ArrayDeque<>();
        int p = 0,n = tokens.length;
        while(p < n){
            String bit = tokens[p];
            if(set.contains(bit)){
                //从栈中弹出元素
                Integer ele1 = arrayDeque.removeFirst();
                Integer ele2 = arrayDeque.removeFirst();
                arrayDeque.addFirst(getResult(bit,ele1,ele2));
            }else{
                arrayDeque.addFirst(Integer.parseInt(bit));
            }
            p++;
        }
        return arrayDeque.removeFirst();
    }
    //注意运算的次序
    private int getResult(String cal,int ele1,int ele2){
        int result = 0;
        if("+".equals(cal)){
            result = ele2+ele1;
        }else if("-".equals(cal)){
            result = ele2-ele1;
        }else if("*".equals(cal)){
            result = ele2*ele1;
        }else if("/".equals(cal)){
            result = ele2/ele1;
        }
        return result;
    }

    @Test
    public void test(){
        System.out.println(evalRPN(new String[]{"2","1","+","3","*"}));
    }
}
